package com.example.demo.controller;

import com.example.demo.Checker.interChecker;
import com.example.demo.DBmake.PostgreDB;
import com.example.demo.Utils.TokenUtil;
import com.example.demo.api.CommonResult;
import com.example.demo.entity.User;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.Encrypt.*;

@RestController
public class LoginController {
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public CommonResult login(@RequestBody User user){
        /****
         * 数据重验证 保证安全性
         */
        String username = user.getUsername();
        String userPwd = user.getPassword();
        interChecker t = new interChecker(".*\\W.*");


        System.out.println(username+' '+userPwd);
        if(!t.CheckString(username,1,11) || !t.CheckString(userPwd,1,16))  return CommonResult.validateFailed();

        /****
         * 后端数据库验证
         */
        PostgreDB Target = new PostgreDB();

        if(Target.CheckUsername(username)) return CommonResult.validateFailed();

        String salt = Target.GetSalt(username);

        if(salt==null) return CommonResult.validateFailed();

        String EncPwd = EncryptPwd.Encrypt(userPwd,salt);

        if(!Target.CheckPassword(username,EncPwd)) return CommonResult.WrongNameOrPwd();

        int uid = Target.GetUid(username);
        if(uid == -1) return  CommonResult.validateFailed();

        int CK_NO = Target.CheckUserCom(uid);

        if(CK_NO == -1 ) return  CommonResult.validateFailed();

        String token = TokenUtil.sign(uid);
        if(token == null) return  CommonResult.validateFailed();

        TokenUtil.verify(token);
        if(CK_NO==0) return  CommonResult.success(uid,token);
        return CommonResult.FirSuccess(uid,token);
    }
}
